#include "consumersys.h"
#include "ui_consumersys.h"


ConsumerSYS::ConsumerSYS(QString username, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ConsumerSYS)
{
    ui->setupUi(this);
    this->username = username;
    client = new Client();

    modelInit();
    consumer = new Consumer(username);

    connect(ui->editBtn, &QPushButton::clicked, this, &ConsumerSYS::editUserInfo);
    connect(ui->rechargeBtn, &QPushButton::clicked, this, &ConsumerSYS::handleRecharge);
    connect(ui->sendBtn, &QPushButton::clicked, this, &ConsumerSYS::handleSend);
    connect(ui->switchBtn, &QPushButton::clicked, [=](){
        static int i = 0;
        ui->stackedWidget->setCurrentIndex((i++)  % 4);
    });
    connect(ui->recvBtn, &QPushButton::clicked, this, &ConsumerSYS::handleRecv);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    connect(ui->refreshBtn, &QPushButton::clicked, this, &ConsumerSYS::refreshExpressInfo);
    connect(ui->refreshBtn, &QPushButton::clicked, this, &ConsumerSYS::refreshInfo);
    connect(ui->searchBtn, &QPushButton::clicked, this, &ConsumerSYS::search);



    connect(ui->confirmSendBtn, &QPushButton::clicked, [=](){

        QString receiver = ui->recvEdit->text();
        QDateTime t = QDateTime::currentDateTime();
        QString sendTime = t.toString("yyyy-MM-dd");
        qsrand(t.time().second());
        int randNum = qrand() % 9000 + 1000; // 生成1000-9999的随机数
        QString id = t.toString("yyyyMMdd") + QString::number(randNum);

        int type = ui->typeBox->currentIndex();
        double unit = ui->unitEdit->text().toDouble();
        if (type == Article::NORMAL)    art = new Normal(sendTime, id, unit);
        else if (type == Article::FRAG) art = new Fragile(sendTime, id, unit);
        else    art = new Book(sendTime, id, unit);
        double price = art->getPrice();
        qDebug() << "价格为:" << price;
        if (!consumer->pay(price)) {
            QMessageBox::warning(this, "提示", "余额不足");
            return;
        }

        Admin *admin = new Admin("admin");
        admin->charge(price);
        delete admin;

        art->packet(this->username, receiver);
        QString command = art->sent();
        qDebug() << command;
        client->sendMsg(command);
        QTimer::singleShot(1000,[=](){
            client->sendMsg(QString("用户 %1 发送快递#").arg(username));
        });
        //client->sendMsg(QString("用户 %1 发送快递#").arg(username));
        //delete art;

        refreshExpressInfo();
        refreshInfo(); // 更新余额
    });

    connect(ui->confirmBtn, &QPushButton::clicked, [=](){
        QString name = ui->nameEdit->text();
        QString password = ui->passwordEdit->text();
        QString phone = ui->phoneEdit->text();
        QString address = ui->addressEdit->text();
        QString str = QString("UPDATE userinfo SET name = '%1', phone = '%2',"
                              "address = '%3' WHERE username = '%4'").arg(name)
                .arg(phone).arg(address).arg(this->username);
        QString str1 = QString("UPDATE login SET password = '%1' WHERE username = '%2'")
                .arg(password).arg(this->username);
        //QSqlQuery query;
        //query.exec(str);
        //query.exec(str1);


        ui->confirmBtn->setEnabled(false);
        ui->editBtn->setEnabled(true);
        qDebug() << "客户端数据：" << str;
        client->sendMsg(str);
        refreshInfo();
    });


    refreshInfo();
    refreshExpressInfo();
}

ConsumerSYS::~ConsumerSYS()
{
    delete ui;
    client->disConnect();
}

void ConsumerSYS::editUserInfo()
{
    ui->editBtn->setEnabled(false);
    ui->confirmBtn->setEnabled(true);
    ui->nameEdit->setEnabled(true);
    ui->passwordEdit->setEchoMode(QLineEdit::Normal);
    ui->passwordEdit->setEnabled(true);
    ui->phoneEdit->setEnabled(true);
    ui->addressEdit->setEnabled(true);


}

void ConsumerSYS::refreshInfo()
{

    QSqlQuery query, q;
    query.prepare(QString("SELECT * FROM userinfo WHERE username = '%1'")
                  .arg(this->username));
    query.exec();
    if (query.next()) {
        ui->usernameEdit->setText(query.value(0).toString());
        q.exec(QString("SELECT * FROM login WHERE username = '%1'").arg(this->username));
        q.next();
        ui->passwordEdit->setText(q.value(1).toString());
        ui->nameEdit->setText(query.value(1).toString());
        ui->phoneEdit->setText(query.value(2).toString());
        ui->balanceEdit->setText(query.value(3).toString() + "元");
        ui->addressEdit->setText(query.value(4).toString());
    }
    ui->nameEdit->setEnabled(false);
    ui->usernameEdit->setEnabled(false);
    ui->passwordEdit->setEnabled(false);
    ui->passwordEdit->setEchoMode(QLineEdit::Password);
    ui->phoneEdit->setEnabled(false);
    ui->addressEdit->setEnabled(false);
    ui->confirmBtn->setEnabled(false);
    ui->balanceEdit->setEnabled(false);
}

void ConsumerSYS::refreshExpressInfo()
{
    ui->recvEdit->setEnabled(false);
    ui->typeBox->setEnabled(false);
    ui->confirmSendBtn->setEnabled(false);
    ui->unitEdit->setEnabled(false);
    ui->sendBtn->setEnabled(true);

    model->select();
    model2->select();
}

void ConsumerSYS::handleRecharge()
{
    double money = QInputDialog::getDouble(this, "充值", "请输入充值金额");
    double curMoney = consumer->charge(money);
    ui->balanceEdit->setText(QString::number(curMoney) + "元");

}

void ConsumerSYS::handleSend()
{
    ui->recvEdit->setEnabled(true);
    ui->typeBox->setEnabled(true);
    ui->confirmSendBtn->setEnabled(true);
    ui->unitEdit->setEnabled(true);
    ui->sendBtn->setEnabled(false);

}

void ConsumerSYS::handleRecv()
{
    int row = ui->tableView_2->currentIndex().row();

    // 错误处理
    QString status = model2->index(row, 6).data().toString();
    if (status == "已签收" || status == "等待揽收") {
        QMessageBox::warning(this, "错误", "非法操作！");
        return;
    }

    QString recvTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm");
    QString id = model2->index(row, 0).data().toString(); // 根据id查找快递;
//    QSqlQuery query;
//    query.prepare(QString("UPDATE expressinfo SET status = '已签收', receivetime = '%1' WHERE "
//                          "id = '%2'").arg(recvTime).arg(id));
//    query.exec();
    client->sendMsg(QString("UPDATE expressinfo SET status = '已签收', receivetime = '%1' WHERE "
                            "id = '%2'").arg(recvTime).arg(id));
    QTimer::singleShot(1000,[=](){
        client->sendMsg(QString("用户 %1 签收快递#").arg(username));
    });
    refreshExpressInfo();
}

void ConsumerSYS::modelInit()
{
    model = new QSqlTableModel(this);
    model2 = new QSqlTableModel(this);
    model3 = new QSqlTableModel(this);
    model->setTable("expressinfo");
    model->setHeaderData(0, Qt::Horizontal, "订单号");
    model->setHeaderData(1, Qt::Horizontal, "物品类型");
    model->setHeaderData(2, Qt::Horizontal, "寄件人");
    model->setHeaderData(3, Qt::Horizontal, "寄件时间");
    model->setHeaderData(4, Qt::Horizontal, "收件人");
    model->setHeaderData(5, Qt::Horizontal, "快递员");
    model->setHeaderData(6, Qt::Horizontal, "物流状态");
    model->setHeaderData(7, Qt::Horizontal, "收件时间");
    model->setHeaderData(8, Qt::Horizontal, "价格");

    model->setFilter(QString("sender = '%1'").arg(username));
    model->select();
    ui->tableView->setModel(model);
    model2->setTable("expressinfo");
    model2->setFilter(QString("receiver = '%1'").arg(username));
    model2->setHeaderData(0, Qt::Horizontal, "订单号");
    model2->setHeaderData(1, Qt::Horizontal, "物品类型");
    model2->setHeaderData(2, Qt::Horizontal, "寄件人");
    model2->setHeaderData(3, Qt::Horizontal, "寄件时间");
    model2->setHeaderData(4, Qt::Horizontal, "收件人");
    model2->setHeaderData(5, Qt::Horizontal, "快递员");
    model2->setHeaderData(6, Qt::Horizontal, "物流状态");
    model2->setHeaderData(7, Qt::Horizontal, "收件时间");
    model2->setHeaderData(8, Qt::Horizontal, "价格");
    model2->select();
    ui->tableView_2->setModel(model2);

    model3->setTable("expressinfo");
    model3->setHeaderData(0, Qt::Horizontal, "订单号");
    model3->setHeaderData(1, Qt::Horizontal, "物品类型");
    model3->setHeaderData(2, Qt::Horizontal, "寄件人");
    model3->setHeaderData(3, Qt::Horizontal, "寄件时间");
    model3->setHeaderData(4, Qt::Horizontal, "收件人");
    model3->setHeaderData(5, Qt::Horizontal, "快递员");
    model3->setHeaderData(6, Qt::Horizontal, "物流状态");
    model3->setHeaderData(7, Qt::Horizontal, "收件时间");
    ui->tableView_3->setModel(model3);

}

void ConsumerSYS::search()
{
    int i = ui->searchTypeBox->currentIndex();
    QString arg = ui->searchEdit->text();
    if (i == 0)
        model3->setFilter(QString("receiver = '%1' and sender = '%2'").arg(arg).arg(username));
    else if (i == 1)
        model3->setFilter(QString("sendTime = '%1' and sender = '%2'").arg(arg).arg(username));
    else
        model3->setFilter(QString("id = '%1' and sender = '%2'").arg(arg).arg(username));
    model3->select();
    if (!ui->tableView_3->verticalHeader()->count())
        QMessageBox::warning(this, "提示", "未查询到有效数据");
}



